﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Collections;
using Jillzhang.Wcf.HostJIT.Services;

namespace Jillzhang.Wcf.HostJIT.Dispatcher
{
    [ServiceContract]
    public interface IRounter
    {
        [OperationContract(Action = "*", ReplyAction = "*")]
        Message ProcessMessage(Message msg);
    }

    [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
    public class Dispatcher : IRounter
    {
        public static readonly Hashtable hostTable = new Hashtable();
        public Message ProcessMessage(Message msg)
        {
            string to = msg.Headers.To.ToString();           
            string serviceName = "";
            //todo:if no host,host first
            if (to.IndexOf("8031") > -1)
            {
                if (!hostTable.ContainsKey("Calculator"))
                {
                    ServiceHost host = new ServiceHost(typeof(Calculator));
                    host.Opened += new EventHandler(delegate(object sender, EventArgs arg)
                    {
                        Console.WriteLine("Calculator service is opened!");
                    });
                    host.Open();
                    hostTable.Add("Calculator", host);
                }
                serviceName = "Calculator";
            }
            else
            {
                if (!hostTable.ContainsKey("Activity"))
                {
                    ServiceHost host = new ServiceHost(typeof(Activity));
                    host.Opened += new EventHandler(delegate(object sender, EventArgs arg)
                    {
                        Console.WriteLine("activity service is opened!");
                    });
                    host.Open();
                    hostTable.Add("Activity", host);
                }
                serviceName = "Activity";
            }
            //todo:rounter the message
            using (ChannelFactory<IRounter> channelFactory = new ChannelFactory<IRounter>(serviceName))
            {
                var chanenl = channelFactory.CreateChannel();
                using (chanenl as IDisposable)
                {
                    return chanenl.ProcessMessage(msg);
                }
            }

        }
    }
}
